package com.starblink.android.basic.bridge

import android.content.Context
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ProcessUtils
import com.blankj.utilcode.util.Utils
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.network.base.BaseApiConfig
import com.starblink.android.basic.network.base.BaseSiteSwitch
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.log.SKLogger
import com.starblink.web.IBridgeInvokeWebProcess
import kotlin.system.exitProcess
import com.starblink.basic.util.ActivityStackManage

//通用交互中转站
class CommonBridge : IBridgeCommand {
    private val TAG="IBridgeCommand"
    companion object{
        var preLoadUrlBridgeI:PreLoadUrlBridgeI?=null //预加载
    }
    override fun exec(params: JsonObject?, callback: IBridgeInvokeWebProcess?) {
        SKLogger.d(TAG,"${ProcessUtils.getCurrentProcessName()} --- $params")
        params?.let {
            val commonKey=it.get("commonKey").asString
            val params=(it.get("params")?:"").toJson()
            val gson= Gson()
            when(commonKey){
                BridgeCommand.Common.switchSite->{
                    //同步切换站点
                    val sitStringUpCase=gson.fromJson(params, String::class.java)
                    BaseSiteSwitch.switchSite(sitStringUpCase,callback = {})
                }
                BridgeCommand.Common.previousEvent->{
                    //同步埋点前置位
                    val previousEvent=gson.fromJson(params, String::class.java)
                    GTrackerAssistUtils.previousEvent=previousEvent
                }
                BridgeCommand.Common.resetClient->{
                    //同步请求头
                    SkGqlClient.resetClient()
                }
                BridgeCommand.Common.preLoadUrl->{
                    //预加载web
                    val cacheUrl=gson.fromJson(params, String::class.java)
                    preLoadUrlBridgeI?.preLoadUrl(Utils.getApp(),cacheUrl)
                }
                BridgeCommand.Common.exitApp->{
                    //退出app
                    exitProcess(0)
                }
                BridgeCommand.Common.clearUserAgentData->{
                    //清空web的UserAgent
                    UserDataCenter.clearUserAgentData()
                }
                BridgeCommand.Common.toHomeWish->{
                    //跳首页心愿单页面
                    FlowBus.intFlowBusNotify(FlowConst.WISH_INDEX_CHANGE, 3)
                }
                else -> {}
            }
        }
    }
}

interface PreLoadUrlBridgeI{
    fun preLoadUrl(context: Context, cacheUrl: String)
}